package liuhe.manager;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONArray;
import org.json.JSONObject;

import liuhe.tools.Common;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class MergeManager {
	public JSONObject mergeData = new JSONObject();
	public JSONObject mergeDataOld = new JSONObject();
	public JSONObject historyMergeDatas = new JSONObject();
	public JSONObject historyMergeDatasOld = new JSONObject();
	private  ReadWriteLock weifengLock = new ReentrantReadWriteLock();
	private  ReadWriteLock wanliLock = new ReentrantReadWriteLock();
	private  ReadWriteLock wanliLockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock cs2Lock = new ReentrantReadWriteLock();
	private  ReadWriteLock cs2LockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock xjsLock = new ReentrantReadWriteLock();
	private  ReadWriteLock xjsLockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock acLock = new ReentrantReadWriteLock();
	private  ReadWriteLock acLockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock futeLock = new ReentrantReadWriteLock();
	private  ReadWriteLock futeLockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock wbLock = new ReentrantReadWriteLock();
	private  ReadWriteLock shiwanLock = new ReentrantReadWriteLock();
	private  ReadWriteLock shiwanLockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock tianziLock = new ReentrantReadWriteLock();
	private  ReadWriteLock taiheLock = new ReentrantReadWriteLock();
	private  ReadWriteLock taiheLockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock jiarunLock = new ReentrantReadWriteLock();
	private  ReadWriteLock jiarunLockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock gutongLock = new ReentrantReadWriteLock();
	private  ReadWriteLock gutongLockOld = new ReentrantReadWriteLock();
	private  ReadWriteLock yingtaiLock = new ReentrantReadWriteLock();
	private  ReadWriteLock yingtaiLockOld = new ReentrantReadWriteLock();
	
	public JSONArray weifengData = new JSONArray();
	public JSONArray wanliData = new JSONArray();
	public JSONArray wanliDataOld = new JSONArray();
	public JSONArray cs2Data = new JSONArray();
	public JSONArray cs2DataOld = new JSONArray();
	public JSONArray xjsData = new JSONArray();
	public JSONArray xjsDataOld = new JSONArray();
	public JSONArray acData = new JSONArray();
	public JSONArray acDataOld = new JSONArray();
	public JSONArray futeData = new JSONArray();
	public JSONArray futeDataOld = new JSONArray();
	public JSONArray wbData = new JSONArray();
	public JSONArray shiwanData = new JSONArray();
	public JSONArray shiwanDataOld = new JSONArray();
	public JSONArray tianziData = new JSONArray();
	public JSONArray taiheData = new JSONArray();
	public JSONArray taiheDataOld = new JSONArray();
	public JSONArray jiarunData = new JSONArray();
	public JSONArray jiarunDataOld = new JSONArray();
	public JSONArray gutongData = new JSONArray();
	public JSONArray gutongDataOld = new JSONArray();
	public JSONArray yingtaiData = new JSONArray();
	public JSONArray yingtaiDataOld = new JSONArray();
	
	private String lastSaveTime = "";
	private String lastSaveTimeOld = "";
	
	private  ReadWriteLock usefulLock = new ReentrantReadWriteLock();
	private  ReadWriteLock usefulLockOld = new ReentrantReadWriteLock();
	public int usefulAccountNum = 0;
	public int usefulAccountNumOld = 0;
	
	public void addUsefulAccountNum(int i) {
		usefulLock.writeLock().lock();
		usefulAccountNum+=i;
		usefulLock.writeLock().unlock();
	}
	
	public void addUsefulAccountNumOld(int i) {
		usefulLockOld.writeLock().lock();
		usefulAccountNumOld+=i;
		usefulLockOld.writeLock().unlock();
	}
	
	public String getMergeData() {
		return mergeData.toString();
	}
	
	public void saveMergeData() {
		try {
			if(isInTime()==false)
				return;
			boolean hasSuccess = false;
			String currIssue = "";
			SimpleDateFormat dfMin = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String saveTime = dfMin.format(System.currentTimeMillis());
			if(lastSaveTime.equals(saveTime)) {
				return;
			}
			//���ҵ�һ��ץȡ�ɹ�����վ������ȡ����
			for (String key : mergeData.keySet()) {
	            // ��ȡÿ������Ӧ��ֵ
				JSONArray ja = mergeData.getJSONArray(key);
				
				for(int i = 0; i<ja.length();i++) {
					JSONObject jb = ja.getJSONObject(i);
					if(jb.getString("msg").equals("SUCCESS")&&(System.currentTimeMillis() - jb.getLong("grabtime")<20*60*1000)) {
		            	currIssue = jb.getString("currIssue");
		            	hasSuccess = true;
		            	break;
		            }
				}
	        }
			
			
			
			if(hasSuccess==true&&!currIssue.equals("")) {
				recoverMergeDataFromfile(currIssue);
				historyMergeDatas.put(saveTime, mergeData);
				File file = new File("data/" + currIssue
						+ ".data");
				BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));
				fwlocal.append(historyMergeDatas.toString());
				fwlocal.newLine();
				fwlocal.flush();
				fwlocal.close();
				lastSaveTime = saveTime;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getHistoryData(String issue, String inputTimeStr) {
		try {
			if(issue.equals("")) {
		        // �����ļ���·��
		        String folderPath = "data";  // �滻Ϊ����ļ���·��
		        File folder = new File(folderPath);

		        if (!folder.exists() || !folder.isDirectory()) {
		            System.out.println("ָ��·����Ч�����ļ���");
		            return null;
		        }

		        // ��ȡ�ļ����������� ".data" ��β���ļ�
		        File[] files = folder.listFiles((dir, name) -> name.endsWith(".data"));
		        
		        if (files == null || files.length == 0) {
		            System.out.println("û���ҵ��� .data ��β���ļ�");
		            return null;
		        }

		        // ������ʽ��ȡ���ֲ���
		        Pattern pattern = Pattern.compile("(\\d+)\\.data");

		        // ���ڴ洢������ֺͶ�Ӧ���ļ�
		        int maxNumber = Integer.MIN_VALUE;
		        File maxFile = null;

		        // �����ļ���������������ļ�
		        for (File file : files) {
		            Matcher matcher = pattern.matcher(file.getName());
		            if (matcher.find()) {
		                int number = Integer.parseInt(matcher.group(1));
		                if (number > maxNumber) {
		                    maxNumber = number;
		                    maxFile = file;
		                }
		            }
		        }
		        
		        // ���������ֵ��ļ�������ȡ�ļ�����
		        if (maxFile != null) {
		            System.out.println("�ҵ����������ļ�: " + maxFile.getName());
		            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(maxFile), "UTF-8"))) {
		                String line;
		                if ((line = reader.readLine()) != null) {
		                	if(line.contains("{")) {
		                		JSONObject jsonObject = new JSONObject(line);
		                        // ��������ʱ���ʽ����
		                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
		                        LocalTime inputTime = LocalTime.parse(inputTimeStr, DateTimeFormatter.ofPattern("HH:mm"));

		                        // �洢���ʱ��� key �Ͷ�Ӧ�� value
		                        String closestTimeKey = null;
		                        JSONObject closestTimeValue = null;
		                        Duration minDuration = Duration.ofHours(24);  // ��ʼ��Ϊ�����ܵ�ʱ���

		                        // ���� JSON ���󣬼���ÿ��ʱ��������ʱ��Ĳ��
		                        for (String key : jsonObject.keySet()) {
		                            // ֻ��עʱ�䲿�֣�����ʱ�䲢��ȡ HH:mm
		                            LocalTime keyTime = LocalTime.parse(key.substring(11), DateTimeFormatter.ofPattern("HH:mm"));

		                            // ����ʱ���������ڲ��֣�����Сʱ�ͷ��ӵĲ��
		                            Duration duration = Duration.between(inputTime, keyTime).abs();

		                            // �����ǰʱ����С�������
		                            if (duration.compareTo(minDuration) < 0) {
		                                minDuration = duration;
		                                closestTimeKey = key;
		                                closestTimeValue = jsonObject.getJSONObject(key);
		                            }
		                        }

		                        // ������ʱ���Ӧ�� key �� value
		                        if (closestTimeKey != null) {
		                            System.out.println("�����ʱ�� key: " + closestTimeKey);
		                            System.out.println("��Ӧ�� value: " + closestTimeValue);
		                            return closestTimeValue.toString();
		                        } else {
		                            System.out.println("û���ҵ���Ч��ʱ���");
		                        }
		                	}                    
		                }
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        } else {
		            System.out.println("û���ҵ������������ļ�");
		        }
			}else {
				BufferedReader reader = null; //��
				
				File dir = new File("data");
				if (dir.exists()) {
				} else {
					dir.mkdirs();
				}
			 
				File file = new File("data/" + issue
						+ ".data");
				
				
				if(!file.exists()){
					return null;
				}else{
					reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); // ָ����ȡ�ļ��ı����ʽ��Ҫ��д��ĸ�ʽһ�£����������������,				
					String str = null;
									
					
					if ((str = reader.readLine()) != null) {
						if(str.contains("{")) {
	                		JSONObject jsonObject = new JSONObject(str);

	                        LocalTime inputTime = LocalTime.parse(inputTimeStr, DateTimeFormatter.ofPattern("HH:mm"));

	                        // �洢���ʱ��� key �Ͷ�Ӧ�� value
	                        String closestTimeKey = null;
	                        JSONObject closestTimeValue = null;
	                        Duration minDuration = Duration.ofHours(24);  // ��ʼ��Ϊ�����ܵ�ʱ���

	                        // ���� JSON ���󣬼���ÿ��ʱ��������ʱ��Ĳ��
	                        for (String key : jsonObject.keySet()) {
	                            // ֻ��עʱ�䲿�֣�����ʱ�䲢��ȡ HH:mm
	                            LocalTime keyTime = LocalTime.parse(key.substring(11), DateTimeFormatter.ofPattern("HH:mm"));

	                            // ����ʱ���������ڲ��֣�����Сʱ�ͷ��ӵĲ��
	                            Duration duration = Duration.between(inputTime, keyTime).abs();

	                            // �����ǰʱ����С�������
	                            if (duration.compareTo(minDuration) < 0) {
	                                minDuration = duration;
	                                closestTimeKey = key;
	                                closestTimeValue = jsonObject.getJSONObject(key);
	                            }
	                        }

	                        // ������ʱ���Ӧ�� key �� value
	                        if (closestTimeKey != null) {
	                            System.out.println("�����ʱ�� key: " + closestTimeKey);
	                            System.out.println("��Ӧ�� value: " + closestTimeValue);
	                            return closestTimeValue.toString();
	                        } else {
	                            System.out.println("û���ҵ���Ч��ʱ���");
	                        }
						}
					}
					reader.close();
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void recoverMergeDataFromfile(String currIssue) {
		try {

			BufferedReader reader = null; //��
			
			File dir = new File("data");
			if (dir.exists()) {
			} else {
				dir.mkdirs();
			}
		 
			File file = new File("data/" + currIssue
					+ ".data");
			
			
			if(!file.exists()){
				return;
			}else{
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); // ָ����ȡ�ļ��ı����ʽ��Ҫ��д��ĸ�ʽһ�£����������������,				
				String str = null;
								
				
				if ((str = reader.readLine()) != null) {
					if(str.contains("{")) {
						historyMergeDatas = new JSONObject(str);
					}
				}
				reader.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	public void initCurrentData() {
        // �����ļ���·��
        String folderPath = "data";  // �滻Ϊ����ļ���·��
        File folder = new File(folderPath);

        if (!folder.exists() || !folder.isDirectory()) {
            System.out.println("ָ��·����Ч�����ļ���");
            return;
        }

        // ��ȡ�ļ����������� ".data" ��β���ļ�
        File[] files = folder.listFiles((dir, name) -> name.endsWith(".data"));
        
        if (files == null || files.length == 0) {
            System.out.println("û���ҵ��� .data ��β���ļ�");
            return;
        }

        // ������ʽ��ȡ���ֲ���
        Pattern pattern = Pattern.compile("(\\d+)\\.data");

        // ���ڴ洢������ֺͶ�Ӧ���ļ�
        int maxNumber = Integer.MIN_VALUE;
        File maxFile = null;

        // �����ļ���������������ļ�
        for (File file : files) {
            Matcher matcher = pattern.matcher(file.getName());
            if (matcher.find()) {
                int number = Integer.parseInt(matcher.group(1));
                if (number > maxNumber) {
                    maxNumber = number;
                    maxFile = file;
                }
            }
        }

        // ���������ֵ��ļ�������ȡ�ļ�����
        if (maxFile != null) {
            System.out.println("�ҵ����������ļ�: " + maxFile.getName());
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(maxFile), "UTF-8"))) {
                String line;
                if ((line = reader.readLine()) != null) {
                	if(line.contains("{")) {
                		JSONObject jsonObject = new JSONObject(line);
                        // ��������ʱ���ʽ����
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

                        // �洢���ʱ��� key �Ͷ�Ӧ�� value
                        String maxTimeKey = null;
                        JSONObject maxTimeValue = null;
                        LocalDateTime maxTime = LocalDateTime.MIN;

                        // ���� JSON ����
                        Iterator<String> keys = jsonObject.keys();
                        while (keys.hasNext()) {
                            String key = keys.next();
                            LocalDateTime currentTime = LocalDateTime.parse(key, formatter);

                            // �����ǰʱ�������������ʱ��Ͷ�Ӧ�� value
                            if (currentTime.isAfter(maxTime)) {
                                maxTime = currentTime;
                                maxTimeKey = key;
                                maxTimeValue = jsonObject.getJSONObject(key);
                            }
                        }

                        // ������ʱ���Ӧ�� key �� value
                        if (maxTimeKey != null) {
                            System.out.println("���ʱ��� key: " + maxTimeKey);
                            System.out.println("��Ӧ�� value: " + maxTimeValue);
                            mergeData = maxTimeValue; 
                        } else {
                            System.out.println("û���ҵ���Ч��ʱ���");
                        }
                	}                    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("û���ҵ������������ļ�");
        }
	}
	
	public void construcMergeData() {
		try {

			int grabSuccessNum = weifengData.length()+
								 wanliData.length()+
								 cs2Data.length()+
								 xjsData.length() + 
								 acData.length() +
								 futeData.length() +
								 shiwanData.length()+
								 tianziData.length() +
								 taiheData.length() +
								 jiarunData.length() + 
								 gutongData.length()+
								 yingtaiData.length();
			
//			Common.logOut("weifengData length:"+ weifengData.length());
//			Common.logOut("wanliData length:"+ wanliData.length());
//			Common.logOut("cs2Data length:"+ cs2Data.length());
//			Common.logOut("xjsData length:"+ xjsData.length());
//			Common.logOut("acData length:"+ acData.length());
//			Common.logOut("futeData length:"+ futeData.length());
//			Common.logOut("shiwanData length:"+ shiwanData.length());
//			Common.logOut("tianziData length:"+ tianziData.length());
//			Common.logOut("taiheData length:"+ taiheData.length());
//			Common.logOut("jiarunData length:"+ taiheData.length());
			
			Common.logOut("grabSuccessNum :"+grabSuccessNum + "usefulAccountNum:" +  usefulAccountNum);
			
			if(grabSuccessNum<usefulAccountNum) {
				return;
			}
			
			Common.logOut("ALL IS GOOD");
			
			if(!isInTime()) {
				return;
			}
			
			weifengLock.readLock().lock();
			wanliLock.readLock().lock();
			cs2Lock.readLock().lock();
			xjsLock.readLock().lock();
			acLock.readLock().lock();
			futeLock.readLock().lock();
			wbLock.readLock().lock();
			shiwanLock.readLock().lock();
			tianziLock.readLock().lock();
			taiheLock.readLock().lock();
			jiarunLock.readLock().lock();
			gutongLock.readLock().lock();
			yingtaiLock.readLock().lock();
			
			mergeData.put("威风", new JSONArray(weifengData.toString()));
			mergeData.put("万利", new JSONArray(wanliData.toString()));
			mergeData.put("CS2", new JSONArray(cs2Data.toString()));
			mergeData.put("XJS", new JSONArray(xjsData.toString()));
			mergeData.put("AC", new JSONArray(acData.toString()));
			mergeData.put("福特", new JSONArray(futeData.toString()));
			mergeData.put("WB", new JSONArray(wbData.toString()));
			mergeData.put("试玩", new JSONArray(shiwanData.toString()));
			mergeData.put("天子", new JSONArray(tianziData.toString()));
			mergeData.put("泰合", new JSONArray(taiheData.toString()));
			mergeData.put("佳润", new JSONArray(jiarunData.toString()));
			mergeData.put("古铜", new JSONArray(gutongData.toString()));
			mergeData.put("盈泰", new JSONArray(yingtaiData.toString()));
			
			saveMergeData();
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		weifengLock.readLock().unlock();
		wanliLock.readLock().unlock();
		cs2Lock.readLock().unlock();
		xjsLock.readLock().unlock();
		acLock.readLock().unlock();
		futeLock.readLock().unlock();
		wbLock.readLock().unlock();
		shiwanLock.readLock().unlock();
		tianziLock.readLock().unlock();
		taiheLock.readLock().unlock();
		jiarunLock.readLock().unlock();
		gutongLock.readLock().unlock();
		yingtaiLock.readLock().unlock();
	}
	
	public boolean isInTime() {
		try {
			LocalTime now = LocalTime.now();
	        LocalTime start = LocalTime.of(18, 50); 
	        LocalTime end = LocalTime.of(21, 30);
	        if (!now.isBefore(start) && !now.isAfter(end)) {
	        	return true;
	        } else {
	            return false;
	        }
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	

	
	public void updateWeifengData(String str) {
		try {
			weifengLock.writeLock().lock();
			weifengData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		weifengLock.writeLock().unlock();
	}
	
	public void updateWanliData(String str) {
		try {
			wanliLock.writeLock().lock();
			wanliData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		wanliLock.writeLock().unlock();
	}
	
	public void updateCS2Data(String str) {
		try {
			cs2Lock.writeLock().lock();
			cs2Data = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		cs2Lock.writeLock().unlock();
	}
	
	
	public void updateXJSData(String str) {
		try {
			xjsLock.writeLock().lock();
			xjsData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		xjsLock.writeLock().unlock();
	}
	
	public void updateACData(String str) {
		try {
			acLock.writeLock().lock();
			acData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		acLock.writeLock().unlock();
	}
	
	public void updateFuteData(String str) {
		try {
			futeLock.writeLock().lock();
			futeData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		futeLock.writeLock().unlock();
	}
	
	public void updateWBData(String str) {
		try {
			wbLock.writeLock().lock();
			wbData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		wbLock.writeLock().unlock();
	}
	


	public void updateShiwanData(String str) {
		try {
			shiwanLock.writeLock().lock();
			shiwanData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		shiwanLock.writeLock().unlock();
	}

	public void updateTianziData(String str) {
		try {
			tianziLock.writeLock().lock();
			tianziData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		tianziLock.writeLock().unlock();
	}

	public void updateTaiheData(String str) {
		try {
			taiheLock.writeLock().lock();
			taiheData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		taiheLock.writeLock().unlock();
	}
	
	
	
	public void updateJiarunData(String str) {
		try {
			jiarunLock.writeLock().lock();
			jiarunData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		jiarunLock.writeLock().unlock();
	}
	
	
	
	public void updateGutongData(String str) {
		try {
			gutongLock.writeLock().lock();
			gutongData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		gutongLock.writeLock().unlock();
	}
	
	public void updateYingtaiData(String str) {
		try {
			yingtaiLock.writeLock().lock();
			yingtaiData = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		yingtaiLock.writeLock().unlock();
	}
	
	
	
	
	
	
	
	//老澳门六合彩
	public String getMergeDataOld() {
		return mergeDataOld.toString();
	}
	
	public void saveMergeDataOld() {
		try {
			if(isInTimeOld()==false)
				return;
			boolean hasSuccess = false;
			String currIssue = "";
			SimpleDateFormat dfMin = new SimpleDateFormat("yyyy-MM-dd HH:mm");
			String saveTime = dfMin.format(System.currentTimeMillis());
			if(lastSaveTimeOld.equals(saveTime)) {
				return;
			}
			//���ҵ�һ��ץȡ�ɹ�����վ������ȡ����
			for (String key : mergeDataOld.keySet()) {
	            // ��ȡÿ������Ӧ��ֵ
				JSONArray ja = mergeDataOld.getJSONArray(key);
				for(int i = 0; i<ja.length();i++) {
					JSONObject jb = ja.getJSONObject(i);
					if(jb.getString("msg").equals("SUCCESS")&&(System.currentTimeMillis() - jb.getLong("grabtime")<20*60*1000)) {
		            	currIssue = jb.getString("currIssue");
		            	hasSuccess = true;
		            	break;
		            }
				}
	        }
			
			
			
			if(hasSuccess==true&&!currIssue.equals("")) {
				recoverMergeDataFromfileOld(currIssue);
				historyMergeDatasOld.put(saveTime, mergeDataOld);
				File file = new File("olddata/" + currIssue
						+ ".data");
				BufferedWriter fwlocal = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, false), "UTF-8"));
				fwlocal.append(historyMergeDatasOld.toString());
				fwlocal.newLine();
				fwlocal.flush();
				fwlocal.close();
				lastSaveTimeOld = saveTime;
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public String getHistoryDataOld(String issue, String inputTimeStr) {
		try {
			if(issue.equals("")) {
		        // �����ļ���·��
		        String folderPath = "olddata";  // �滻Ϊ����ļ���·��
		        File folder = new File(folderPath);

		        if (!folder.exists() || !folder.isDirectory()) {
		            System.out.println("ָ��·����Ч�����ļ���");
		            return null;
		        }

		        // ��ȡ�ļ����������� ".data" ��β���ļ�
		        File[] files = folder.listFiles((dir, name) -> name.endsWith(".data"));
		        
		        if (files == null || files.length == 0) {
		            System.out.println("û���ҵ��� .data ��β���ļ�");
		            return null;
		        }

		        // ������ʽ��ȡ���ֲ���
		        Pattern pattern = Pattern.compile("(\\d+)\\.data");

		        // ���ڴ洢������ֺͶ�Ӧ���ļ�
		        int maxNumber = Integer.MIN_VALUE;
		        File maxFile = null;

		        // �����ļ���������������ļ�
		        for (File file : files) {
		            Matcher matcher = pattern.matcher(file.getName());
		            if (matcher.find()) {
		                int number = Integer.parseInt(matcher.group(1));
		                if (number > maxNumber) {
		                    maxNumber = number;
		                    maxFile = file;
		                }
		            }
		        }
		        
		        // ���������ֵ��ļ�������ȡ�ļ�����
		        if (maxFile != null) {
		            System.out.println("�ҵ����������ļ�: " + maxFile.getName());
		            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(maxFile), "UTF-8"))) {
		                String line;
		                if ((line = reader.readLine()) != null) {
		                	if(line.contains("{")) {
		                		JSONObject jsonObject = new JSONObject(line);
		                        // ��������ʱ���ʽ����
		                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
		                        LocalTime inputTime = LocalTime.parse(inputTimeStr, DateTimeFormatter.ofPattern("HH:mm"));

		                        // �洢���ʱ��� key �Ͷ�Ӧ�� value
		                        String closestTimeKey = null;
		                        JSONObject closestTimeValue = null;
		                        Duration minDuration = Duration.ofHours(24);  // ��ʼ��Ϊ�����ܵ�ʱ���

		                        // ���� JSON ���󣬼���ÿ��ʱ��������ʱ��Ĳ��
		                        for (String key : jsonObject.keySet()) {
		                            // ֻ��עʱ�䲿�֣�����ʱ�䲢��ȡ HH:mm
		                            LocalTime keyTime = LocalTime.parse(key.substring(11), DateTimeFormatter.ofPattern("HH:mm"));

		                            // ����ʱ���������ڲ��֣�����Сʱ�ͷ��ӵĲ��
		                            Duration duration = Duration.between(inputTime, keyTime).abs();

		                            // �����ǰʱ����С�������
		                            if (duration.compareTo(minDuration) < 0) {
		                                minDuration = duration;
		                                closestTimeKey = key;
		                                closestTimeValue = jsonObject.getJSONObject(key);
		                            }
		                        }

		                        // ������ʱ���Ӧ�� key �� value
		                        if (closestTimeKey != null) {
		                            System.out.println("�����ʱ�� key: " + closestTimeKey);
		                            System.out.println("��Ӧ�� value: " + closestTimeValue);
		                            return closestTimeValue.toString();
		                        } else {
		                            System.out.println("û���ҵ���Ч��ʱ���");
		                        }
		                	}                    
		                }
		            } catch (IOException e) {
		                e.printStackTrace();
		            }
		        } else {
		            System.out.println("û���ҵ������������ļ�");
		        }
			}else {
				BufferedReader reader = null; //��
				
				File dir = new File("olddata");
				if (dir.exists()) {
				} else {
					dir.mkdirs();
				}
			 
				File file = new File("olddata/" + issue
						+ ".data");
				
				
				if(!file.exists()){
					return null;
				}else{
					reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); // ָ����ȡ�ļ��ı����ʽ��Ҫ��д��ĸ�ʽһ�£����������������,				
					String str = null;
									
					
					if ((str = reader.readLine()) != null) {
						if(str.contains("{")) {
	                		JSONObject jsonObject = new JSONObject(str);

	                        LocalTime inputTime = LocalTime.parse(inputTimeStr, DateTimeFormatter.ofPattern("HH:mm"));

	                        // �洢���ʱ��� key �Ͷ�Ӧ�� value
	                        String closestTimeKey = null;
	                        JSONObject closestTimeValue = null;
	                        Duration minDuration = Duration.ofHours(24);  // ��ʼ��Ϊ�����ܵ�ʱ���

	                        // ���� JSON ���󣬼���ÿ��ʱ��������ʱ��Ĳ��
	                        for (String key : jsonObject.keySet()) {
	                            // ֻ��עʱ�䲿�֣�����ʱ�䲢��ȡ HH:mm
	                            LocalTime keyTime = LocalTime.parse(key.substring(11), DateTimeFormatter.ofPattern("HH:mm"));

	                            // ����ʱ���������ڲ��֣�����Сʱ�ͷ��ӵĲ��
	                            Duration duration = Duration.between(inputTime, keyTime).abs();

	                            // �����ǰʱ����С�������
	                            if (duration.compareTo(minDuration) < 0) {
	                                minDuration = duration;
	                                closestTimeKey = key;
	                                closestTimeValue = jsonObject.getJSONObject(key);
	                            }
	                        }

	                        // ������ʱ���Ӧ�� key �� value
	                        if (closestTimeKey != null) {
	                            System.out.println("�����ʱ�� key: " + closestTimeKey);
	                            System.out.println("��Ӧ�� value: " + closestTimeValue);
	                            return closestTimeValue.toString();
	                        } else {
	                            System.out.println("û���ҵ���Ч��ʱ���");
	                        }
						}
					}
					reader.close();
				}
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public void recoverMergeDataFromfileOld(String currIssue) {
		try {

			BufferedReader reader = null; //��
			
			File dir = new File("olddata");
			if (dir.exists()) {
			} else {
				dir.mkdirs();
			}
		 
			File file = new File("olddata/" + currIssue
					+ ".data");
			
			
			if(!file.exists()){
				return;
			}else{
				reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8")); // ָ����ȡ�ļ��ı����ʽ��Ҫ��д��ĸ�ʽһ�£����������������,				
				String str = null;
								
				
				if ((str = reader.readLine()) != null) {
					if(str.contains("{")) {
						historyMergeDatasOld = new JSONObject(str);
					}
				}
				reader.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	public void initCurrentDataOld() {
        // �����ļ���·��
        String folderPath = "olddata";  // �滻Ϊ����ļ���·��
        File folder = new File(folderPath);

        if (!folder.exists() || !folder.isDirectory()) {
            System.out.println("ָ��·����Ч�����ļ���");
            return;
        }

        // ��ȡ�ļ����������� ".data" ��β���ļ�
        File[] files = folder.listFiles((dir, name) -> name.endsWith(".data"));
        
        if (files == null || files.length == 0) {
            System.out.println("û���ҵ��� .data ��β���ļ�");
            return;
        }

        // ������ʽ��ȡ���ֲ���
        Pattern pattern = Pattern.compile("(\\d+)\\.data");

        // ���ڴ洢������ֺͶ�Ӧ���ļ�
        int maxNumber = Integer.MIN_VALUE;
        File maxFile = null;

        // �����ļ���������������ļ�
        for (File file : files) {
            Matcher matcher = pattern.matcher(file.getName());
            if (matcher.find()) {
                int number = Integer.parseInt(matcher.group(1));
                if (number > maxNumber) {
                    maxNumber = number;
                    maxFile = file;
                }
            }
        }

        // ���������ֵ��ļ�������ȡ�ļ�����
        if (maxFile != null) {
            System.out.println("�ҵ����������ļ�: " + maxFile.getName());
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(maxFile), "UTF-8"))) {
                String line;
                if ((line = reader.readLine()) != null) {
                	if(line.contains("{")) {
                		JSONObject jsonObject = new JSONObject(line);
                        // ��������ʱ���ʽ����
                        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

                        // �洢���ʱ��� key �Ͷ�Ӧ�� value
                        String maxTimeKey = null;
                        JSONObject maxTimeValue = null;
                        LocalDateTime maxTime = LocalDateTime.MIN;

                        // ���� JSON ����
                        Iterator<String> keys = jsonObject.keys();
                        while (keys.hasNext()) {
                            String key = keys.next();
                            LocalDateTime currentTime = LocalDateTime.parse(key, formatter);

                            // �����ǰʱ�������������ʱ��Ͷ�Ӧ�� value
                            if (currentTime.isAfter(maxTime)) {
                                maxTime = currentTime;
                                maxTimeKey = key;
                                maxTimeValue = jsonObject.getJSONObject(key);
                            }
                        }

                        // ������ʱ���Ӧ�� key �� value
                        if (maxTimeKey != null) {
                            System.out.println("���ʱ��� key: " + maxTimeKey);
                            System.out.println("��Ӧ�� value: " + maxTimeValue);
                            mergeDataOld = maxTimeValue; 
                        } else {
                            System.out.println("û���ҵ���Ч��ʱ���");
                        }
                	}                    
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("û���ҵ������������ļ�");
        }
	}
	
	public void construcMergeDataOld() {
		try {
			int grabSuccessNum = shiwanDataOld.length() + 
								wanliDataOld.length() +
								acDataOld.length() +
								xjsDataOld.length() +
								cs2DataOld.length() +
								futeDataOld.length() +
								taiheDataOld.length() +
								jiarunDataOld.length() +
								gutongDataOld.length() +
								yingtaiDataOld.length();

//			Common.logOut("shiwanDataOld length:"+ shiwanDataOld.length());
//			Common.logOut("wanliDataOld length:"+ wanliDataOld.length());
//			Common.logOut("acDataOld length:"+ acDataOld.length());
//			Common.logOut("xjsDataOld length:"+ xjsDataOld.length());

			Common.logOut("old grabSuccessNum :"+grabSuccessNum + "usefulAccountNumOld:" +  usefulAccountNumOld);
			
			if(grabSuccessNum<usefulAccountNumOld) {
				return;
			}
			
			Common.logOut("ALL IS GOOD [OLD]");
			
			if(!isInTimeOld()) {
				return;
			}
			
			shiwanLockOld.readLock().lock();
			wanliLockOld.readLock().lock();
			acLockOld.readLock().lock();
			xjsLockOld.readLock().lock();
			cs2LockOld.readLock().lock();
			futeLockOld.readLock().lock();
			taiheLockOld.readLock().lock();
			jiarunLockOld.readLock().lock();
			gutongLockOld.readLock().lock();
			yingtaiLockOld.readLock().lock();
			
			mergeDataOld.put("试玩", new JSONArray(shiwanDataOld.toString()));
			mergeDataOld.put("万利", new JSONArray(wanliDataOld.toString()));
			mergeDataOld.put("ac", new JSONArray(acDataOld.toString()));
			mergeDataOld.put("xjs", new JSONArray(xjsDataOld.toString()));
			mergeDataOld.put("cs2", new JSONArray(cs2DataOld.toString()));
			mergeDataOld.put("福特", new JSONArray(futeDataOld.toString()));
			mergeDataOld.put("泰和", new JSONArray(taiheDataOld.toString()));
			mergeDataOld.put("佳润", new JSONArray(jiarunDataOld.toString()));
			mergeDataOld.put("古铜", new JSONArray(gutongDataOld.toString()));
			mergeDataOld.put("盈泰", new JSONArray(yingtaiDataOld.toString()));
			
			saveMergeDataOld();
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		shiwanLockOld.readLock().unlock();
		wanliLockOld.readLock().unlock();
		acLockOld.readLock().unlock();
		xjsLockOld.readLock().unlock();
		cs2LockOld.readLock().unlock();
		futeLockOld.readLock().unlock();
		taiheLockOld.readLock().unlock();
		jiarunLockOld.readLock().unlock();
		gutongLockOld.readLock().unlock();
		yingtaiLockOld.readLock().unlock();
	}
	

	
	public boolean isInTimeOld() {
		try {
			LocalTime now = LocalTime.now();
	        LocalTime start = LocalTime.of(10, 50); 
	        LocalTime end = LocalTime.of(21, 30);
	        if (!now.isBefore(start) && !now.isAfter(end)) {
	        	return true;
	        } else {
	            return false;
	        }
		}catch(Exception e) {
			e.printStackTrace();
		}
		return false;
	}
	

	public void updateShiwanDataOld(String str) {
		try {
			shiwanLockOld.writeLock().lock();
			shiwanDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		shiwanLockOld.writeLock().unlock();
	}

	public void updateWanliDataOld(String str) {
		try {
			wanliLockOld.writeLock().lock();
			wanliDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		wanliLockOld.writeLock().unlock();
	}

	public void updateACDataOld(String str) {
		try {
			acLockOld.writeLock().lock();
			acDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		acLockOld.writeLock().unlock();
	}

	public void updateXJSDataOld(String str) {
		try {
			xjsLockOld.writeLock().lock();
			xjsDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		xjsLockOld.writeLock().unlock();
	}

	public void updateCS2DataOld(String str) {
		try {
			cs2LockOld.writeLock().lock();
			cs2DataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		cs2LockOld.writeLock().unlock();
	}

	public void updateFuteDataOld(String str) {
		try {
			futeLockOld.writeLock().lock();
			futeDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		futeLockOld.writeLock().unlock();
	}

	public void updateTaiheDataOld(String str) {
		try {
			taiheLockOld.writeLock().lock();
			taiheDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		taiheLockOld.writeLock().unlock();
		
	}

	public void updateJiarunDataOld(String str) {
		try {
			jiarunLockOld.writeLock().lock();
			jiarunDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		jiarunLockOld.writeLock().unlock();
	}

	public void updateGutongDataOld(String str) {
		try {
			gutongLockOld.writeLock().lock();
			gutongDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		gutongLockOld.writeLock().unlock();
	}

	public void updateYingtaiDataOld(String str) {
		try {
			yingtaiLockOld.writeLock().lock();
			yingtaiDataOld = new JSONArray(str);
		}catch(Exception e) {
			e.printStackTrace();
		}
		yingtaiLockOld.writeLock().unlock();
	}

}
